package commonUtils.filter;

import com.alibaba.fastjson.JSON;
import commonUtils.entities.Restful;
import commonUtils.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 检查用户是否已经完成登录
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //专门进行路径匹配的匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求"+requestURI);
//        2.判断本次请求是否需要处理,定义放行的请求路径
        String[] urls = new String[]{
                "/admins/login",
                "/admins/logout",
                "/admins/**",
//                "/backend/page/login/login.html",
//                "/front/page/login.html",
                "/backend/**",
                "/front/**",
                "/common/**",
//                "/user/sendMsg", //移动端发送短信
//                "/user/login",    //移动端登录
         };
        boolean check = check(urls, requestURI);
        log.info(check+"");
        //3.若不需要处理，直接放行
        if (check){
//            log.info("本次请求不处理："+requestURI);
            filterChain.doFilter(request,response);
            return;
        }


        HttpSession session = request.getSession();
        //4-1.判断登录状态，如果已经登录，直接放行
        Long employee =(Long) session.getAttribute("employee");
        if (employee != null){
            //调用工具类将用户id传入当前线程的公共域
            BaseContext.setCurrentId(employee);
            log.info("用户已登录，用户ID为" +request.getSession().getAttribute("employee") );
            filterChain.doFilter(request,response);
            return;
        }
        //4-2.移动端登录验证
        Long user =(Long) session.getAttribute("user");
        if (user != null){
            //调用工具类将用户id传入当前线程的公共域
            BaseContext.setCurrentId(user);
            log.info("用户已登录，用户ID为" +request.getSession().getAttribute("user") );
            filterChain.doFilter(request,response);
            return;
        }

        log.info("给前端转发送未登录的信息");
        //5.如果未登录的话，则返回登录页面。通过输出流的方式，向客户端页面响应对应的数据
        Restful r = Restful.error("NOTLOGIN");
        PrintWriter writer = response.getWriter();
        String s = JSON.toJSONString(r);
        writer.write(s);

    }

    /**
     * 路径匹配，检查此次请求是否需要放行
     * @param urls  需要放行的URI数组
     * @param requestURI 请求的URI
     * @return 返回是否匹配成功
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean b = PATH_MATCHER.match(url, requestURI);
            if (b){
                return true;
            }
        }
        return false;
    }


}
